//
//  QXMainTabVC.swift
//  QXWeibo
//
//  Created by QinXin on 15/6/23.
//  Copyright © 2015年 labi3285_Lab. All rights reserved.
//

import UIKit

class QXMainTabVC: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 使用 KVC 替换 tabBar （原来的是只读的）
        let mainTabBar = QXMainTabBar()
        setValue(mainTabBar, forKeyPath: "tabBar")
        
        mainTabBar.compoesBtn.addTarget(self, action: "compoesBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        addChildViewControllers()

    }
    
    func compoesBtnClick() {
        let vc = QXSendNewVC.create()
        presentViewController(vc, animated: true, completion: nil)
    }
    
    private func addChildViewControllers() {
        
        let path = NSBundle.mainBundle().pathForResource("ViewControllers.json", ofType: nil)
        
        let data = NSData(contentsOfFile: path!)
        
        do {
            
            // 这里通过json来加载控制器，json可以网络获取，以更新显示效果
            let arr = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
            
            for dic in arr as! [[String: String]] {
                addChildViewController(dic["vcName"]!, title: dic["title"]!, iconName: dic["iconName"]!)
            }
            
        } catch {
            
            print(error)
            
            // 出现异常后直接代码加载控制器
            addChildViewController("QXHomeTableVC", title: "首页", iconName: "tabbar_home")
            addChildViewController("QXMessageTableVC", title: "消息", iconName: "tabbar_message_center")
            addChildViewController("QXDiscoveryTableVC", title: "发现", iconName: "tabbar_discover")
            addChildViewController("QXProfileVC", title: "个人", iconName: "tabbar_profile")
        }

    }
    
    private func addChildViewController(vcName: String, title: String, iconName: String) {
        
        // 取得类名（需要应用作用域）
        let appInfoDic = NSBundle.mainBundle().infoDictionary
        let domain = appInfoDic!["CFBundleExecutable"] as! String
        let vcClass: AnyClass = NSClassFromString(domain + "." + vcName)!
        
        // 实例化
        let vc = vcClass.new() as! UIViewController
        
        vc.title = title;
        vc.tabBarItem.image = UIImage(named: iconName)
        vc.tabBarItem.selectedImage = UIImage(named: "\(iconName)_highlighted")
        
        let nav = UINavigationController(rootViewController: vc)
        addChildViewController(nav)
    }

}
